package com.shaoman.customer.view.activity.base

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.example.androidreviewapp.R
import com.example.androidreviewapp.databinding.ActivityWebviewBinding
import com.shenghuai.bclient.stores.util.ActivityEt.getLayoutRootView

/**
 * Created by liulei
 * 2019/12/27 10:44
 * {描述这个类功能}
 */
abstract class BaseWebViewActivity : AppCompatActivity(R.layout.activity_webview) {

    private val rootBinding by lazy {
        ActivityWebviewBinding.bind(getLayoutRootView())
    }

    private var currentLoadUrl: String = ""
    private var webView: WebView? = null

    protected var backArrowIv: ImageView? = null
    protected var commonTitleTv: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //  initTitleBar(title = "")

        backArrowIv = findViewById<ImageView?>(R.id.backArrowIv)
        backArrowIv?.setOnClickListener { onBackPressed() }

        val webView = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
            LollipopFixedWebView(this)
        } else {
            WebView(this)
        }
        this.webView = webView
        webView.id = R.id.webView

        commonTitleTv = rootBinding.commonTitle

        webView.settings.apply {
            javaScriptEnabled = isJsEnabled()
            domStorageEnabled = true
        }
        webView.webViewClient = MyWebViewClient()
        webView.webChromeClient = MyWebChromeClient()

        configWebView(webView)

        val llp: ViewGroup.LayoutParams =
            RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        if (showTitleBar()) {
            (llp as RelativeLayout.LayoutParams).addRule(RelativeLayout.BELOW, R.id.topBarLL)
        } else {
            rootBinding.topBarLL.isVisible = false
        }
        rootBinding.rootRL.addView(webView, llp)

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                if (currentLoadUrl.isNotEmpty()) {
                    webView.settings.javaScriptEnabled = isJsEnabled()
                    loadUrl(currentLoadUrl)
                } else {
                }
                lifecycle.removeObserver(this)
            }
        })
    }

    open fun showTitleBar(): Boolean {
        return true
    }

    abstract fun isJsEnabled(): Boolean
    abstract fun configWebView(webView: WebView)

    open fun customOverrideUrlLoading(): Boolean {
        return false;
    }

    open fun isUserWebTitle(): Boolean {
        return true;
    }

    fun getWebView(): WebView? {
        return webView
    }

    fun setWillLoadUrl(url: String) {
        currentLoadUrl = url
    }

    fun loadUrl(url: String) {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
            && lifecycle.currentState != Lifecycle.State.DESTROYED
        ) {
            currentLoadUrl = url;
            webView?.loadUrl(url)
        }
    }

    inner class MyWebChromeClient : WebChromeClient() {

        override fun onJsConfirm(
            view: WebView?,
            url: String?,
            message: String?,
            result: JsResult?
        ): Boolean {
            AlertDialog.Builder(this@BaseWebViewActivity)
                .setMessage(message)
                .setPositiveButton(R.string.ok) { _, _ ->
                    result?.confirm()
                }
                .setNegativeButton(R.string.cancel) { _, _ ->
                    result?.cancel()
                }.show()
            return true
        }

        override fun onJsAlert(
            view: WebView?,
            url: String?,
            message: String?,
            result: JsResult?
        ): Boolean {
            AlertDialog.Builder(this@BaseWebViewActivity)
                .setMessage(message)
                .setPositiveButton(R.string.ok) { _, _ ->
                    result?.confirm()
                }
                .setNegativeButton(R.string.cancel) { _, _ ->
                    result?.cancel()
                }.show()
            return true
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            if ((title?.isNotEmpty() == true) && isUserWebTitle()) {
                rootBinding.commonTitle.text = title
            }
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            rootBinding.topProgressbar.visibility = View.VISIBLE
            rootBinding.topProgressbar.progress = newProgress
            if (newProgress >= 98)
                rootBinding.topProgressbar.visibility = View.GONE
        }

        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
            return super.onConsoleMessage(consoleMessage)
        }
    }

    open fun customShouldOverrideUrlLoading(
        view: WebView?,
        url: String,
        request: WebResourceRequest?
    ): Boolean {
        return false
    }

    open fun onPageFinished(view: WebView?, url: String?) {
    }

    inner class MyWebViewClient : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            rootBinding.topProgressbar.visibility = View.GONE
            (this@BaseWebViewActivity).onPageFinished(view, url)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            if (customOverrideUrlLoading()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    return customShouldOverrideUrlLoading(view, request?.url?.path ?: "", request)
                }
            }
            return false
        }

        @Suppress("DEPRECATION")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            if (customOverrideUrlLoading()) {
                return customShouldOverrideUrlLoading(view, url ?: "", null);
            }
            return super.shouldOverrideUrlLoading(view, url)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        webView?.stopLoading()
        webView?.removeAllViews()
        ((webView?.parent) as? ViewGroup)?.removeView(webView)
    }
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class LollipopFixedWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : WebView(context.createConfigurationContext(Configuration()), attrs, defStyleAttr, defStyleRes)